package com.hivekion.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hivekion.common.core.SystemConstant;
import com.hivekion.common.exception.BusinessException;
import com.hivekion.common.redis.RedisUtil;
import com.hivekion.system.domain.SysStatisticsTarget;
import com.hivekion.system.domain.SysStatisticsTargetSum;
import com.hivekion.system.domain.vo.*;
import com.hivekion.system.mapper.SysStatisticsTargetMapper;
import com.hivekion.system.mapper.SysStatisticsTargetSumMapper;
import com.hivekion.system.service.ISysStatisticsTargetService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysStatisticsTargetServiceImpl implements ISysStatisticsTargetService {

      @Autowired
      private SysStatisticsTargetMapper targetMapper;

      @Autowired
      private SysStatisticsTargetClassicServiceImpl targetClassicService;

      @Autowired
      private SysStatisticsTargetSumMapper targetSumMapper;

      @Autowired
      private RedisUtil redisUtil;

      @Override
      public Boolean checkTargetNameUnique(String targetName, String targetId) {
	    LambdaQueryWrapper<SysStatisticsTarget> StatisticsItemLambdaQueryWrapper =
		    Wrappers.lambdaQuery();
	    StatisticsItemLambdaQueryWrapper.eq(SysStatisticsTarget::getName, targetName);
	    if (StringUtils.isNotEmpty(targetId)) {
		  StatisticsItemLambdaQueryWrapper.ne(SysStatisticsTarget::getId, targetId);
	    }
	    List<SysStatisticsTarget> list = targetMapper.selectList(StatisticsItemLambdaQueryWrapper);
	    return list.size() > 0;
      }

      @Override
      public Boolean checkTargetSumNameUnique(String targetName, String targetId) {
	    LambdaQueryWrapper<SysStatisticsTargetSum> StatisticsItemLambdaQueryWrapper =
		    Wrappers.lambdaQuery();
	    StatisticsItemLambdaQueryWrapper.eq(SysStatisticsTargetSum::getName, targetName);
	    if (StringUtils.isNotEmpty(targetId)) {
		  StatisticsItemLambdaQueryWrapper.ne(SysStatisticsTargetSum::getId, targetId);
	    }
	    List<SysStatisticsTargetSum> list =
		    targetSumMapper.selectList(StatisticsItemLambdaQueryWrapper);
	    return list.size() > 0;
      }

      @Override
      public boolean create(SysStatisticsTargetCreateInputVo inputVo) {
	    SysStatisticsTarget item = new SysStatisticsTarget();
	    BeanUtils.copyProperties(inputVo, item);
	    if (inputVo.getTargetType() == null || inputVo.getTargetType().equals("")) {
		  throw new BusinessException(500, "选的指标分类不正确！");
	    }
	    boolean bl =
		    targetClassicService.checkTargetClassicNameUnique(null, inputVo.getTargetType());
	    if (!bl) {
		  throw new BusinessException(500, "选的指标分类不存在！");
	    }
	    bl = targetMapper.insert(item) > 0;
	    if (bl) this.updateRedis();
	    return bl;
      }

      @Override
      public boolean createSum(SysStatisticsTargetSumCreateInputVo inputVo) {
	    SysStatisticsTargetSum item = new SysStatisticsTargetSum();
	    BeanUtils.copyProperties(inputVo, item);

	    boolean bl = targetSumMapper.insert(item) > 0;
	    if (bl) this.updateSumRedis();
	    return bl;
      }

      @Override
      public boolean update(SysStatisticsTargetUpdateInputVo inputVo) {
	    SysStatisticsTarget target = getTarget(inputVo.getId());
	    BeanUtils.copyProperties(inputVo, target);
	    boolean bl = targetMapper.updateById(target) > 0;
	    if (bl) this.updateRedis();
	    return bl;
      }

      private SysStatisticsTarget getTarget(String targetId) {
	    SysStatisticsTarget target = targetMapper.selectById(targetId);
	    if (target == null) {
		  throw new BusinessException(500, "未找到指标信息");
	    }
	    return target;
      }

      @Override
      public boolean delete(String targetId) {

	    boolean bl = targetMapper.deleteById(targetId) > 0;
	    if (bl) this.updateRedis();
	    return bl;
      }

      @Override
      public boolean deleteSum(String targetSumId) {

	    boolean bl = targetSumMapper.deleteById(targetSumId) > 0;
	    if (bl) this.updateRedis();
	    return bl;
      }

      @Override
      public List<SysStatisticsTarget> getTargetListByList(List<String> targetIdList) {

	    LambdaQueryWrapper<SysStatisticsTarget> StatisticsItemLambdaQueryWrapper =
		    Wrappers.lambdaQuery();
	    for (String targetId : targetIdList) {
		  StatisticsItemLambdaQueryWrapper.eq(SysStatisticsTarget::getId, targetId).or();
	    }

	    List<SysStatisticsTarget> list = targetMapper.selectList(StatisticsItemLambdaQueryWrapper);
	    return list;
      }

      @Override
      public List<SysStatisticsTargetSum> getTargetSumListByList(List<String> targetIdList) {

	    LambdaQueryWrapper<SysStatisticsTargetSum> StatisticsItemLambdaQueryWrapper =
		    Wrappers.lambdaQuery();
	    for (String targetSumId : targetIdList) {
		  StatisticsItemLambdaQueryWrapper.eq(SysStatisticsTargetSum::getId, targetSumId).or();
	    }

	    List<SysStatisticsTargetSum> list =
		    targetSumMapper.selectList(StatisticsItemLambdaQueryWrapper);
	    return list;
      }

      @Override
      public SysStatisticsTarget getInfo(String targetId) {
	    SysStatisticsTarget target = targetMapper.selectById(targetId);
	    if (target == null) {
		  throw new BusinessException(500, "未找到指标信息");
	    }
	    return target;
      }

      @Override
      public SysStatisticsTargetSum getSumInfo(String targetSumId) {
	    SysStatisticsTargetSum targetSum = targetSumMapper.selectById(targetSumId);
	    if (targetSum == null) {
		  throw new BusinessException(500, "未找到指标信息");
	    }
	    return targetSum;
      }

      @Override
      public List<SysStatisticsTargetViewVo> getTargetListByClassic(String targetClassicId) {
	    return buildViewVo(getTargetList(targetClassicId));
      }

      public List<SysStatisticsTarget> getTargetList(String targetClassicId) {
	    List<SysStatisticsTarget> allTarget = getAllList();
	    List<SysStatisticsTarget> collect =
		    allTarget.stream()
			    .sorted(Comparator.comparing(SysStatisticsTarget::getSortCode))
			    .collect(Collectors.toList());
	    if (targetClassicId == null) {
		  // TODO 返回全部

		  return collect;
	    }
	    List<SysStatisticsTarget> result = new ArrayList<>();
	    // TODO 增加通过 类型获取
	    List<String> classicList = Arrays.asList(targetClassicId.split(","));
	    collect.forEach(
		    target -> {
			  if (classicList.contains(target.getTargetType())) {
				result.add(target);
			  }
		    });
	    return result;
      }

      private List<SysStatisticsTargetViewVo> buildViewVo(List<SysStatisticsTarget> list) {
	    List<SysStatisticsTargetViewVo> nodes = new ArrayList<>();
	    if (list != null && list.size() > 0) {
		  list.forEach(
			  StatisticsItem -> {
				SysStatisticsTargetViewVo vo = new SysStatisticsTargetViewVo();
				BeanUtils.copyProperties(StatisticsItem, vo);
				nodes.add(vo);
			  });
	    }
	    return nodes;
      }

      private List<SysStatisticsTargetSumViewVo> buildSumViewVo(List<SysStatisticsTargetSum> list) {
	    List<SysStatisticsTargetSumViewVo> nodes = new ArrayList<>();
	    if (list != null && list.size() > 0) {
		  list.forEach(
			  StatisticsItem -> {
				SysStatisticsTargetSumViewVo vo = new SysStatisticsTargetSumViewVo();
				BeanUtils.copyProperties(StatisticsItem, vo);
				nodes.add(vo);
			  });
	    }
	    return nodes;
      }

      @Override
      public List<SysStatisticsTargetSumViewVo> getTargetSumList(String biNameId) {

	    List<SysStatisticsTargetSum> allSumList = getAllSumList();
	    if (biNameId != null) {
		  allSumList =
			  allSumList.stream()
				  .filter(
					  x -> {
						if (x.getBiNameId() == null) {
						      return false;
						}
						return x.getBiNameId().equals(biNameId);
					  })
				  .collect(Collectors.toList());
	    }
	    return buildSumViewVo(allSumList);
      }

      /*
       * redis 缓存数据
       * */
      public List<SysStatisticsTarget> getAllList() {
	    if (redisUtil.hasKey(SystemConstant.redis_target_data)) {
		  List<SysStatisticsTarget> list =
			  JSON.parseArray(
				  redisUtil.get(SystemConstant.redis_target_data).toString(),
				  SysStatisticsTarget.class);
		  return list;
	    } else {
		  List<SysStatisticsTarget> allTarget = targetMapper.selectList(null);
		  redisUtil.set(SystemConstant.redis_target_data, JSON.toJSONString(allTarget));
		  return allTarget;
	    }
      }

      /*
       * redis 缓存数据
       * */
      public List<SysStatisticsTargetSum> getAllSumList() {
	    if (redisUtil.hasKey(SystemConstant.redis_target_sum_data)) {
		  List<SysStatisticsTargetSum> list =
			  JSON.parseArray(
				  redisUtil.get(SystemConstant.redis_target_sum_data).toString(),
				  SysStatisticsTargetSum.class);
		  return list;
	    } else {
		  List<SysStatisticsTargetSum> allTargetSum = targetSumMapper.selectList(null);
		  redisUtil.set(SystemConstant.redis_target_sum_data, JSON.toJSONString(allTargetSum));
		  return allTargetSum;
	    }
      }

      private void updateRedis() {
	    List<SysStatisticsTarget> allTarget = targetMapper.selectList(null);
	    redisUtil.set(SystemConstant.redis_target_data, JSON.toJSONString(allTarget));
      }

      private void updateSumRedis() {
	    List<SysStatisticsTarget> allTarget = targetMapper.selectList(null);
	    redisUtil.set(SystemConstant.redis_target_sum_data, JSON.toJSONString(allTarget));
      }
}
